<template>
  <div class="container">
    <div class="mb10">
      <el-text class="mx-1"> 查询条件：</el-text>
    </div>
    <el-row :gutter="10">
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.order_sn" placeholder="xxxx订单号" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.out_bill_no" placeholder="商户订单号" clearable></el-input>
      </el-col>
      <!-- <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.pay_type" placeholder="请选择支付方式" multiple clearable>
          <el-option v-for="item in orderPayType" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col> -->
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.pay_source" placeholder="请选择支付来源" clearable>
          <el-option v-for="item in billPaySource" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.is_delivery" placeholder="请选择核销状态" clearable>
          <el-option v-for="item in deliveryStatus" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.is_pay" placeholder="请选择是否已支付" clearable>
          <el-option v-for="item in selectWhether" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-space wrap>
          <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
          <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
        </el-space>
      </el-col>
    </el-row>
    <div class="mb10">
      <el-text class="mx-1"> 查询结果：</el-text>
    </div>
    <el-table :data="tableList" border class="table" row-key="id" ref="multipleTableRef" v-loading="loading" :reserve-selection="true" @row-dblclick="rowDblclick">
      <el-table-column type="index" align="center"> </el-table-column>
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="order_sn" label="xxxx订单号" align="center"> </el-table-column>
      <el-table-column prop="out_bill_no" label="商户订单号" align="center"> </el-table-column>
      <el-table-column prop="title" label="账单标题" align="center"> </el-table-column>
      <el-table-column prop="issue" label="期数" align="center"> </el-table-column>
      <el-table-column prop="staging_time" label="账单日期" align="center" :formatter="(row: IInstallmentBill) => handleVerifyFormatDate(row.staging_time)"> </el-table-column>
      <el-table-column prop="price" label="金额" align="center"> </el-table-column>
      <el-table-column prop="is_pay" label="支付状态" align="center">
        <template #default="scope">
          <div class="w-tag">
            <el-tag :type="scope.row.is_pay === 1 ? 'success' : 'danger'">{{ scope.row.is_pay === 1 ? "已支付" : "未支付" }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="pay_time" label="支付时间" align="center" :formatter="(row: IInstallmentBill) => handleVerifyFormatDate(row.pay_time)"> </el-table-column>
      <el-table-column prop="pay_type_name" label="支付方式" align="center">
        <template #default="scope">
          <div class="ibDraggable" v-if="scope.row.tradeLog !== null">
            <div>{{ orderPayTypeObj[scope.row.tradeLog.type] }}</div>
          </div>
          <div class="ibDraggable" v-else>
            <div>--</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="pay_source_name" label="支付来源" align="center"></el-table-column>
      <el-table-column prop="is_delivery_name" label="核销状态" align="center">
        <template #default="scope">
          <div class="w-tag" v-if="scope.row.is_delivery_name !== ''">
            <el-tag :type="scope.row.is_delivery === 1 ? 'success' : 'danger'">{{ scope.row.is_delivery_name }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center">
        <template #default="scope">
          <div class="control-flex">
            <el-button type="primary" link :icon="EditPen" v-permission="'updatePrice'" @click="handleUpdatePrice(scope.row)">修改账单金额</el-button>
            <el-button type="primary" link :icon="EditPen" v-permission="'updatePrice'" @click="handleCheckPayStatus(scope.row)">检查支付状态</el-button>
            <div v-permission="'updatePayStatus'">
              <el-popconfirm placement="top" width="160" title="你确定要修改吗?" @confirm="handleUpdatePayStatus(scope.row)">
                <template #reference>
                  <el-button link :icon="EditPen" type="primary">修改账单支付状态</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-if="scope.row.tradeLog !== null && ['dyPay', 'dyAliPay'].includes(scope.row.tradeLog.type) && scope.row.is_delivery == 0">
              <el-popconfirm placement="top" width="160" title="你确定要核销吗?" @confirm="handlePushDelivery(scope.row)">
                <template #reference>
                  <el-button link :icon="Close" type="success">去核销</el-button>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="searchCondition.size"
        :current-page="searchCondition.current"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="total"
        :hide-on-single-page="false">
      </el-pagination>
    </div>
    <!-- 修改手机号弹框 -->
    <UpdatePriceDialog v-model:dialog="dialogVisible" v-model:form="updatePriceFrom" @handleSuccess="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
import UpdatePriceDialog from "@/components/rentMachineManage/installmentBill/UpdatePriceDialog.vue";
import { Close, EditPen, Search, Refresh } from "@element-plus/icons-vue";
import { handleVerifyFormatDate } from "@/utils/utils";
import { useState } from "@/hooks/useState.ts";
import { useDictData } from "@/hooks/network/useDictData";
import type { IDictData } from "@/types/dict";
import type { IChangePriceInfo, IInstallmentBill, ISearchInstallmentBill, IUpdateStatusInfo } from "@/types/rentMachineManage/installmentBill";
import { getCheckPayStatusInfo, getTnstallmentBillInfo, putTnstallmentBillPayStatusInfo, putTnstallmentBillPushDeliveryInfo } from "@/utils/api/installmentBill";
import type { IKeyedMap } from "@/types/common";
let { getDictData } = useDictData();
const { disabledbtn, loading, toggleState } = useState();
/* 是否信息 */
const selectWhether = ref<Array<IDictData>>([]);
/* 支付来源 */
const billPaySource = ref<Array<IDictData>>([]);
/* 核销状态 */
const deliveryStatus = ref<Array<IDictData>>([]);
/* 支付平台类型 */
const orderPayType = ref<Array<IDictData>>([]);
/* 支付平台类型对象 */
const orderPayTypeObj = ref<IKeyedMap<string>>({});

const dialogVisible = ref(false);
/* 暴露一个方法给父组件使用 */
defineExpose({
  /* 这一步关键，在setup语法糖中使用时 */
  getTableInfo
});
const multipleTableRef = useTemplateRef("multipleTableRef"); /* 列表组件的引用 */

const total = ref(0);
const searchCondition = reactive<ISearchInstallmentBill>({
  order_sn: "",
  out_bill_no: "",
  pay_source: "",
  is_delivery: "",
  is_pay: "",
  size: 20,
  current: 1
});
const tableList = ref<Array<IInstallmentBill>>([]);
const updatePriceFrom = reactive<IChangePriceInfo>({
  id: 0,
  price: ""
});

onMounted(() => {
  getTableInfo();
});
/* 搜索 */
function searchInfo() {
  searchCondition.current = 1;
  searchCondition.size = 20;
  getTableInfo();
}

/**
 * 重置搜索内容
 */
function resetSearch() {
  searchCondition.order_sn = "";
  searchCondition.out_bill_no = "";
  searchCondition.pay_source = "";
  searchCondition.is_delivery = "";
  searchCondition.is_pay = "";

  searchCondition.current = 1;
  searchCondition.size = 20;

  getTableInfo();
}

/* 请求：获取表格中数据 */
function getTableInfo() {
  toggleState(true);
  getTnstallmentBillInfo<IInstallmentBill, ISearchInstallmentBill>(searchCondition)
    .then(res => {
      tableList.value = res.result.data;
      total.value = res.result.total;
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 显示第几页 */
function handleCurrentChange(val: number) {
  searchCondition.current = val;
  getTableInfo();
}

/* 每页显示几条 */
function handleSizeChange(val: number) {
  searchCondition.current = 1;
  searchCondition.size = val;
  getTableInfo();
}

/* 双击当前行 */
function rowDblclick(row: IInstallmentBill) {
  multipleTableRef.value!.toggleRowSelection(row);
}
/* 修改账单支付状态 */
function handlePushDelivery(row: IInstallmentBill) {
  toggleState(true);
  putTnstallmentBillPushDeliveryInfo({
    id: row.id
  })
    .then(res => {
      ElMessage.success(res.msg);
      handleChangeRefundStatus(row.id, 1);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 账单支付状态信息 */
function handleCheckPayStatus(row: IInstallmentBill) {
  toggleState(true);
  getCheckPayStatusInfo({
    id: row.id
  })
    .then(res => {
      ElMessage.success(res.msg);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 修改账单支付状态 */
function handleUpdatePayStatus(row: IInstallmentBill) {
  toggleState(true);
  const is_pay = row.is_pay === 0 ? 1 : 0;
  putTnstallmentBillPayStatusInfo<unknown, IUpdateStatusInfo>({
    id: row.id,
    is_pay
  })
    .then(res => {
      ElMessage.success(res.msg);
      const item = tableList.value.find(order => order.id === row.id);
      if (!item) return;
      item.is_pay = is_pay;
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 修改状态 */
function handleChangeRefundStatus(id: number, status: number) {
  const item = tableList.value.find(order => order.id === id);
  if (!item) return;
  item.is_delivery = status;
  const _status = deliveryStatus.value.find(item => item.dictValue == status + "");
  if (!_status) return;
  item.is_delivery_name = _status.dictLabel;
}

/* 修改账单金额 */
function handleUpdatePrice(row: IInstallmentBill) {
  updatePriceFrom.id = row.id;
  updatePriceFrom.price = row.price;
  dialogVisible.value = true;
}
/* 修改数据成功 */
function handleSuccess() {
  const item = tableList.value.find(order => order.id === updatePriceFrom.id);
  if (!item) return;
  item.price = updatePriceFrom.price;
}

getDictData("WHETHER", selectWhether);
getDictData("BILL_PAY_SOURCE", billPaySource);
getDictData("DOUYIN_DELIVERY_STATUS", deliveryStatus);
getDictData("ORDER_PAY_TYPE", orderPayType, (list: Array<IDictData>) => {
  list.forEach(item => {
    orderPayTypeObj.value[item.dictValue] = item.dictLabel;
  });
  console.log(orderPayTypeObj.value);
});
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}

.mb10 {
  margin-bottom: 10px;
}
/* 关键：列表右侧操作按钮的对其 */
:deep(.el-space__item) {
  line-height: 15px;
}

.el-button.is-text + .el-button.is-text {
  margin-left: 0;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}
.textAlignCenter {
  text-align: center;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

.w-tag .el-tag {
  margin: 2px 5px;
}
</style>
